﻿using System;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace DaveSexton.Labs
{
	internal static class DispatcherExtensions
	{
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is redirected to Task.")]
		public static Task InvokeAsync(this Dispatcher dispatcher, Action action)
		{
			Contract.Requires(dispatcher != null);
			Contract.Requires(action != null);
			Contract.Ensures(Contract.Result<Task>() != null);

			var task = new TaskCompletionSource<bool>();

			dispatcher.BeginInvoke(() =>
			{
				try
				{
					action();
				}
				catch (Exception ex)
				{
					task.SetException(ex);
					return;
				}

				task.SetResult(true);
			});

			return task.Task;
		}
	}
}